package com.avecsys.quotemanager.dao.system;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.avecsys.quotemanager.constants.BusinessCodes;
import com.avecsys.quotemanager.dao.common.BaseDAOImpl;
import com.avecsys.quotemanager.dao.common.EnumDBRecordStatus;
import com.avecsys.quotemanager.exception.DAOException;
import com.avecsys.quotemanager.pojos.CompanyMasterPojo;

public class SystemUserDAOImpl extends BaseDAOImpl implements SystemUserDAO{

	private static final Log log = LogFactory.getLog(SystemUserDAOImpl.class);
	
	/**
	 * 
	 * @param companyMasterPojo
	 * @return
	 * @throws DAOException
	 */
	public CompanyMasterPojo findSystemCompany(final CompanyMasterPojo companyMasterPojo) throws DAOException
	{
		try
		{
			return (CompanyMasterPojo) getHibernateTemplate().execute(new HibernateCallback<CompanyMasterPojo>()
			{
				@Override
				public CompanyMasterPojo doInHibernate(Session session) throws HibernateException, SQLException
				{
					Criteria criteria = session.createCriteria(companyMasterPojo.getClass());
					criteria.add(Expression.eq("status", EnumDBRecordStatus.ACTIVE.status()));
					criteria.add(Expression.eq("companyType", BusinessCodes.COMPANY_TYPE_SYSTEM));
					List<CompanyMasterPojo> result = criteria.list();
					if (result.size() > 0)
					{
						return (CompanyMasterPojo) result.get(0);
					}
					else
					{
						return null;
					}
				}
			});
		}
		catch (Exception e)
		{
			log.error("findSystemCompany failed", e);
			throw new DAOException(e);
		}
	}
}
